<script setup>
import { ref, computed, onMounted } from 'vue'
import { AddCircleOutline, ArrowDownCircleOutline, SettingsOutline, ArrowUpCircleOutline } from '@vicons/ionicons5'
import { useMessage } from "naive-ui";
import { downloadJsonData } from '@/utils/file'
import { getWebsites, fetchWebsites } from '@/utils/data'
import { getWebsitesFromDb, saveWebsitesToDb, openUrlInBrowser } from '@/utils/utools'
import { validateWebsitesDataFormat } from '@/utils/validate'

const message = useMessage();

const websites = ref([]);
const currentMenu = ref('');
const keywords = ref("");
const websiteForm = ref({
  type: '',
  url: '',
  title: '',
});
const websiteRules = {
  title: {
    required: true,
    message: "请输入网站标题",
    trigger: ["input", "blur"]
  },
  url: {
    required: true,
    message: "请输入网站地址",
    trigger: ["input", "blur"]
  },
  type: {
    required: true,
    message: "请输入网站类型",
    trigger: ["input", "blur"]
  },
}
const websiteFormRef = ref(null);
const fileInput = ref(null);

onMounted(async () => {
  try {
    const dbWebsites = getWebsitesFromDb();
    console.log('dbWebsites', dbWebsites);
    if (dbWebsites) {
      websites.value = dbWebsites;
    } else {
      const websitesData = await fetchWebsites()
      validateWebsitesDataFormat(websitesData)
      websites.value = websitesData;
    }
  } catch (error) {
    console.error(error);
    websites.value = getWebsites();
  }
  currentMenu.value = websites.value && websites.value[0]?.type
});

const menuOptions = computed(() => {
  const uniqueTypes = new Set(websites.value.map(it => it.type));
  return Array.from(uniqueTypes).map(type => ({
    label: type,
    key: type,
  }));
});

function handleUpdateMenu(key, menu) {
  currentMenu.value = key;
}

function handleCloseTag(wb) {
  websites.value = websites.value.filter(it => wb.url !== it.url)
}

function handleAddWebsiteClick(e) {
  e.preventDefault();
  websiteFormRef.value?.validate((errors) => {
    if (!errors) {
      websites.value.push(websiteForm.value);
      websiteForm.value = {
        type: '',
        url: '',
        title: '',
      };
      message.success("添加成功");
    } else {
      console.log(errors);
      message.error("请输入完整信息");
    }
  });
}

function triggerFileInput() {
  fileInput.value.click();
}

function handleFileChange(event) {
  const file = fileInput.value.files[0];
  if (!file) {
    message.error('没有选择文件');
    return;
  }

  if (file.type !== 'application/json') {
    message.error('请选择正确的文件类型')
    return;
  }
  const reader = new FileReader();
  reader.onload = (e) => {
    const fileContent = e.target.result;
    try {
      const data = JSON.parse(fileContent);
      validateWebsitesDataFormat(data);
      websites.value = data;
      currentMenu.value = websites.value && websites.value[0].type
      message.success('导入成功');
    } catch (error) {
      message.error('读取配置文件失败，请检查文件内容是否正确：' + JSON.stringify(error));
    }
    fileInput.value.value = null;
  };
  reader.readAsText(file);
}

function handleClickSearch() {
  if (!keywords.value) {
    message.error('请输入搜索内容');
    return;
  }
  let textSearchList = keywords.value.split(/\r?\n/);
  let textUrlList = websites.value.filter(it => it.checked).map(it => it.url);
  for (let keyword of textSearchList) {
    if (!keyword || keyword.trim() === '') {
      continue;
    }
    for (let url of textUrlList) {
      let realUrl = url.replace("{0}", keyword);
      openUrlInBrowser(realUrl);
    }
  }
  saveWebsitesToDb(JSON.parse(JSON.stringify(websites.value)));
}

function handleKeywordsKeyDown(e) {
  if (e.ctrlKey && e.keyCode == 13) {
    handleClickSearch();
  }
}

</script>

<template>
  <n-space vertical>
    <n-layout class="b">
      <n-layout-header bordered>
        <n-menu mode="horizontal" :options="menuOptions" :on-update:value="handleUpdateMenu" />
      </n-layout-header>
      <n-layout class="content">
        <n-tag v-for="wb in websites" :key="wb.url" v-show="wb.type === currentMenu" closable
          @close="handleCloseTag(wb)" class="wb-item">
          <n-checkbox v-model:checked="wb.checked" :value="wb.url">
            <n-tooltip trigger="hover">
              <template #trigger>
                {{ wb.title }}
              </template>
              {{ wb.url }}
            </n-tooltip>
          </n-checkbox>
        </n-tag>
      </n-layout>
    </n-layout>
    <n-space class="b p-10">
      <n-tag v-for="wb in websites.filter(it => it.checked)" :key="wb.url" class="wb-item">
        {{ wb.title }}
      </n-tag>
    </n-space>
    <n-input @keydown.enter="handleKeywordsKeyDown" v-model:value="keywords" type="textarea" class="text-input"
      placeholder="请输入要搜索的关键词，每一个关键词占一行，点击搜索或者按Ctrl + Enter打开浏览器进行搜索"></n-input>
    <n-button type="success" @click="handleClickSearch">
      搜索
    </n-button>
  </n-space>

  <n-float-button :right="40" :bottom="40" position="fixed" type="primary" menu-trigger="click">
    <n-icon>
      <SettingsOutline />
    </n-icon>
    <template #menu>
      <n-float-button type="primary">
        <n-popover placement="top-end" trigger="click">
          <template #trigger>
            <n-tooltip trigger="hover">
              <template #trigger>
                <n-icon>
                  <AddCircleOutline />
                </n-icon>
              </template>
              添加网站
            </n-tooltip>
          </template>
          <n-card title="添加网站" class="form-card">
            <n-form ref="websiteFormRef" :label-width="80" :model="websiteForm" :rules="websiteRules">
              <n-form-item label="网站地址" path="url">
                <n-input v-model:value="websiteForm.url"
                  placeholder="例如：https://www.baidu.com/s?wd={0}，{0}会被替换成搜索关键词" />
              </n-form-item>
              <n-form-item label="网站标题" path="title">
                <n-input v-model:value="websiteForm.title" placeholder="例如：百度" />
              </n-form-item>
              <n-form-item label="网站分组" path="type">
                <n-input v-model:value="websiteForm.type" placeholder="例如：搜索引擎" />
              </n-form-item>
              <n-form-item>
                <n-button attr-type="button" @click="handleAddWebsiteClick">
                  添加
                </n-button>
              </n-form-item>
            </n-form>
          </n-card>
        </n-popover>
      </n-float-button>
      <n-float-button type="primary" @click="downloadJsonData(websites, 'utools-batch-search-config.json')">
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-icon>
              <ArrowDownCircleOutline />
            </n-icon>
          </template>
          导出网站
        </n-tooltip>
      </n-float-button>
      <n-float-button type="primary" @click="triggerFileInput">
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-icon>
              <ArrowUpCircleOutline />
            </n-icon>
          </template>
          导入网站
        </n-tooltip>
      </n-float-button>
    </template>
  </n-float-button>

  <input type="file" ref="fileInput" style="display: none;" @change="handleFileChange" />

</template>

<style scoped>
.b {
  border: 1px #ccc solid;
  border-radius: var(--n-border-radius);
}

.p-10 {
  padding: 10px;
}

.content {
  height: 100px;
  padding: 10px;
}

.text-input {
  height: 300px;
}

.form-card {
  width: 550px;
}

.wb-item {
  margin-right: 5px;
}
</style>
